from flask import request, g
from models.card_consumption import CardConsumption
from models.card_package import CardPackage
from models.store import Store
from models.user import User
from models.product import Product
from extensions import db
from utils.auth import token_required
from flask_restx import Namespace, Resource, fields
from datetime import datetime
from models.user_store import UserStore
from sqlalchemy import or_, and_,select, join,desc

api = Namespace('card_consumptions', description='卡包消费管理相关接口')

base_response = api.model('BaseResponse', {
    'status': fields.String(description='响应状态'),
    'message': fields.String(description='响应消息')
})

# 定义员工业绩数据模型
staff_performance_model = api.model('StaffPerformance', {
    'staff_id': fields.Integer(description='员工ID'),
    'staff_name': fields.String(description='员工姓名'),
    'consumption_day': fields.Integer(description='消费日'),
    'consumption_month': fields.Integer(description='消费月'),
    'consumption_year': fields.Integer(description='消费年'),
    'performance': fields.Float(description='业绩金额'),
    'commission': fields.Float(description='提成金额')
})

# 修改员工业绩响应模型
staff_performance_response = api.inherit('StaffPerformanceResponse', base_response, {
    'data': fields.Nested(api.model('StaffPerformancePagination', {
        'list': fields.List(fields.Nested(staff_performance_model)),
        'pagination': fields.Nested(api.model('Pagination', {
            'total': fields.Integer(description='总记录数'),
            'page': fields.Integer(description='当前页码'),
            'limit': fields.Integer(description='每页数量')
        }))
    }))
})

# 修改员工业绩明细响应模型
staff_performance_list_response = api.inherit('StaffPerformanceResponse', base_response, {
    'data': fields.Nested(api.model('StaffPerformancePagination', {
        'list': fields.List(fields.Nested(api.model('TransactionDetail', {
            'id': fields.Integer(description='消费记录ID'),
            'transaction_type': fields.Integer(description='交易类型'),
            'income_type': fields.Integer(description='收支类型'),
            'amount_used': fields.Float(description='金额'),
            'consumption_date': fields.DateTime(description='消费日期'),
            'consumption_day': fields.Integer(description='消费日'),
            'consumption_month': fields.Integer(description='消费月'),
            'consumption_year': fields.Integer(description='消费年'),
            'user_name': fields.String(description='用户姓名'),
            'product_name': fields.String(description='产品名称'),
            'description': fields.String(description='备注说明')
        }))),
        'pagination': fields.Nested(api.model('Pagination', {
            'total': fields.Integer(description='总记录数'),
            'page': fields.Integer(description='当前页码'),
            'limit': fields.Integer(description='每页数量')
        }))
    }))
})

# 定义商品模型
product_model = api.model('Product', {
    'id': fields.Integer(description='商品ID'),
    'name': fields.String(description='商品名称'),
    'price': fields.Float(description='商品价格'),
    'description': fields.String(description='商品描述'),
    'store_id': fields.Integer(description='店铺ID'),
    'category': fields.String(description='商品类别'),
    'commission_rate': fields.Float(description='提成比例'),
    'status': fields.Integer(description='状态(0:下架, 1:上架)'),
    'created_at': fields.DateTime(description='创建时间'),
    'updated_at': fields.DateTime(description='更新时间'),
    'is_deleted': fields.Boolean(description='是否删除')
})

card_consumption_model = api.model('CardConsumption', {
    'id': fields.Integer(description='消费记录ID'),
    'income_type': fields.Integer(description='收支类型(0:支出, 1:收入)'),
    'transaction_type': fields.Integer(description='交易类型(1:卡包充值, 2:成本支出, 3:现金单次消费, 4:卡包消费, 5:卡包提成, 6:单笔业务提成)'),
    'store_id': fields.Integer(description='店铺ID'),
    'card_package_id': fields.Integer(description='卡包ID'),
    'user_id': fields.Integer(description='用户ID'),
    'staff_id': fields.Integer(required=True, description='员工ID'),
    'product_id': fields.Integer(description='产品ID'),
    'consumption_date': fields.DateTime(description='消费日期'),
    'amount_used': fields.Float(description='消费金额或次数'),
    'remaining_amount': fields.Float(description='剩余金额或次数'),
    'card_type': fields.String(description='卡包类型(comprehensive/per_use)'),
    'description': fields.String(description='说明'),
    'is_invalid': fields.Boolean(description='是否失效'),
    'product': fields.Nested(product_model, description='商品信息')
})



card_consumption_response = api.inherit('CardConsumptionResponse', base_response, {
    'data': fields.Nested(card_consumption_model)
})

# 定义分页数据模型
pagination_data = api.model('PaginationData', {
    'list': fields.List(fields.Nested(card_consumption_model)),
    'total': fields.Integer(description='总记录数'),
    'page': fields.Integer(description='当前页码'),
    'limit': fields.Integer(description='每页数量')
})

# 修改列表响应模型
card_consumption_list_response = api.inherit('CardConsumptionListResponse', base_response, {
    'data': fields.Nested(pagination_data)
})

@api.route('/transaction', strict_slashes=False)
class TransactionRecord(Resource):
    @api.doc('新增收支记录')
    @api.expect(api.model('TransactionRequest', {
        'store_id': fields.Integer(required=True, description='店铺ID'),
        'staff_id': fields.Integer(required=True, description='员工ID'),
        'transaction_type': fields.Integer(required=True, description='交易类型(1:卡包充值, 2:成本支出, 3:现金单次消费, 4:卡包消费, 5:卡包提成, 6:单笔业务提成)'),
        'income_type': fields.Integer(required=True, description='收支类型(0:支出, 1:收入)'),
        'amount_used': fields.Float(required=True, description='金额'),
        'description': fields.String(description='备注'),
        'card_package_id': fields.Integer(description='卡包ID(可选)'),
        'user_id': fields.Integer(description='用户ID(可选)'),
        'product_id': fields.Integer(description='产品ID(可选)')
    }))
    @api.marshal_with(card_consumption_response)
    @token_required
    def post(self):
        """新增收支记录"""
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['store_id', 'staff_id', 'transaction_type', 'income_type', 'amount_used']
        for field in required_fields:
            if field not in data:
                return {
                    'status': 'error',
                    'message': f'缺少必填字段: {field}'
                }, 400
        curent_user = g.current_identity
        # staff_id获取用户，store_id获取店铺
        store = Store.query.filter_by(store_id=data['store_id']).first()
        staff = User.query.filter_by(user_id=data['staff_id']).first()
        if not store or not staff:
            return {
              'status': 'error',
              'message': '店铺或员工不存在'
            }, 404

        try:
            # 创建消费记录
            consumption = CardConsumption(
                transaction_type=data['transaction_type'],
                income_type=data['income_type'],
                store_id=store.id,
                staff_id=staff.id,
                amount_used=data['amount_used'],
                description=data.get('description', ''),
                card_package_id=None,
                user_id=None,
                product_id=None,
                consumption_date=datetime.now(),
                card_type=data.get('card_type'),
                handle_user_id=curent_user.id
            )
            
            db.session.add(consumption)
            db.session.commit()
            
            return {
                'status': 'success',
                'message': '收支记录创建成功',
                'data': consumption.to_dict()
            }, 201
            
        except Exception as e:
            db.session.rollback()
            return {
                'status': 'error',
                'message': f'创建收支记录失败: {str(e)}'
            }, 500

@api.route('/open_card', strict_slashes=False)
class OpenCard(Resource):
    @api.doc('开卡记录')
    @api.expect(card_consumption_model)
    @api.marshal_with(card_consumption_response)
    @token_required
    def post(self):
        """客户开卡记录"""
        data = request.get_json()
        
        # 创建消费记录
        consumption = CardConsumption(
            income_type=1,  # 收入
            transaction_type=1,  # 卡包充值
            store_id=data['store_id'],
            card_package_id=data['card_package_id'],
            user_id=data['user_id'],
            staff_id=data['staff_id'],
            consumption_date=datetime.now(),
            amount_used=data['amount_used'],
            remaining_amount=data['amount_used'],
            card_type=data['card_type'],
            description=data.get('description', '开卡充值')
        )
        
        db.session.add(consumption)
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '开卡记录创建成功',
            'data': consumption.to_dict()
        }, 201

@api.route('/user', strict_slashes=False)
class CardConsumptionRecord(Resource):
    @api.doc('获取客户消费记录', params={
        'store_id': '店铺ID(必填)',
        'user_id': '用户ID(必填)',
        'page': '页码',
        'limit': '每页数量'
    })
    @api.marshal_with(card_consumption_list_response)
    @token_required
    def get(self):
        """获取客户消费记录列表"""
        # 获取必填参数
        store_id = request.args.get('store_id')
        user_id = request.args.get('user_id')
         # 查询店铺和用户ID
        store = Store.query.filter_by(store_id=store_id).first()
        user = User.query.filter_by(user_id=user_id).first()
        # 验证必填参数
        if not store_id or not user_id:
            return {
                'status': 'error',
                'message': '店铺ID和用户ID为必填项'
            }, 400
            
        # 分页参数
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 10))
        
        # 构建查询
        if not store or not user:
            return {
               'status': 'error',
               'message': '店铺或用户不存在'
            }, 404 
        query = CardConsumption.query.filter_by(
            store_id=store.id,
            user_id=user.id,
            is_invalid=False
        ).filter(
            CardConsumption.transaction_type.in_([1, 3, 4]),  # 1:卡包充值, 3:现金单次消费, 4:卡包消费
            CardConsumption.income_type.in_([1, 3])  # 1:收入, 3:其他收入
        )
        
        # 获取总数
        total = query.count()
        
        # 分页查询
        consumptions = query.order_by(
            CardConsumption.consumption_date.desc()
        ).offset((page - 1) * limit).limit(limit).all()
        
        # 处理结果，添加商品信息
        consumption_list = []
        for consumption in consumptions:
            consumption_dict = consumption.to_dict()
            if consumption.product_id:
                product = Product.query.get(consumption.product_id)
                if product:
                    consumption_dict['product'] = product.to_dict()
            consumption_list.append(consumption_dict)
        
        return {
            'status': 'success',
            'message': '获取成功',
            'data': {
                'list': consumption_list,
                'total': total,
                'page': page,
                'limit': limit
            }
        }, 200

@api.route('/staff', strict_slashes=False)
class CardCommission(Resource):
    @api.doc('获取员工提成记录', params={
        'store_id': '店铺ID(必填)',
        'staff_id': '员工ID(必填)',
        'page': '页码',
        'limit': '每页数量'
    })
    @api.marshal_with(card_consumption_list_response)
    @token_required
    def get(self):
        """获取员工提成记录列表"""
        # 获取必填参数
        store_id = request.args.get('store_id')
        staff_id = request.args.get('staff_id')
 
        # 验证必填参数
        if not store_id or not staff_id:
            return {
                'status': 'error',
                'message': '店铺ID和员工ID为必填项'
            }, 400
                 # 查询店铺和用户ID
        store = Store.query.filter_by(store_id=store_id).first()
        staff = User.query.filter_by(user_id=staff_id).first()
        if not staff or not store:
            return {
              'status': 'error',
              'message': '店铺或员工不存在'
            }, 404
            
        # 分页参数
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 10))
        
        # 构建查询
        query = CardConsumption.query.filter_by(
            store_id=store.id,
            staff_id=staff.id,
            is_invalid=False
        ).filter(
            CardConsumption.transaction_type.in_([5, 6])  # 5:卡包提成, 6:单笔业务提成
        )
        
        # 获取总数
        total = query.count()
        
        # 分页查询
        commissions = query.order_by(
            CardConsumption.consumption_date.desc()
        ).offset((page - 1) * limit).limit(limit).all()
        
        return {
            'status': 'success',
            'message': '获取成功',
            'data': {
                'list': [commission.to_dict() for commission in commissions],
                'total': total,
                'page': page,
                'limit': limit
            }
        }, 200

@api.route('/store', strict_slashes=False)
class ServiceCommission(Resource):
    @api.doc('获取店铺员工提成汇总', params={
        'store_id': '店铺ID(必填)',
        'start_date': '开始日期',
        'end_date': '结束日期',
        'group_by': '时间维度(day/month/year, 默认day)'
    })
    @api.marshal_with(base_response)
    @token_required
    def get(self):
        """获取店铺所有员工提成汇总"""
        store_id = request.args.get('store_id')
        group_by = request.args.get('group_by', 'day')  # 默认按天分组
        
        if not store_id:
            return {
                'status': 'error',
                'message': '店铺ID为必填项'
            }, 400
            
        # 根据时间维度设置分组字段
        if group_by == 'year':
            date_field = CardConsumption.consumption_year
        elif group_by == 'month':
            date_field = CardConsumption.consumption_month
        else:  # day
            date_field = CardConsumption.consumption_day
            
        # 构建基础查询
        query = db.session.query(
            CardConsumption.staff_id,
            User.name.label('staff_name'),
            date_field.label('date'),
            db.func.sum(CardConsumption.amount_used).label('total_commission'),
            db.func.count(CardConsumption.id).label('commission_count')
        ).join(
            User, User.id == CardConsumption.staff_id
        ).filter(
            CardConsumption.store_id == store_id,
            CardConsumption.is_invalid == False,
            CardConsumption.transaction_type.in_([5, 6])
        )
        
        # 添加日期筛选
        start_date = request.args.get('start_date')
        if start_date:
            start_date_int = int(datetime.strptime(start_date, '%Y-%m-%d').strftime('%Y%m%d'))
            query = query.filter(CardConsumption.consumption_day >= start_date_int)
            
        end_date = request.args.get('end_date')
        if end_date:
            end_date_int = int(datetime.strptime(end_date, '%Y-%m-%d').strftime('%Y%m%d'))
            query = query.filter(CardConsumption.consumption_day <= end_date_int)
        
        # 分组并执行查询
        results = query.group_by(
            CardConsumption.staff_id,
            User.name,
            date_field
        ).order_by(
            date_field.desc(),
            CardConsumption.staff_id
        ).all()
        
        # 格式化结果
        commission_summary = [{
            'staff_id': result.staff_id,
            'staff_name': result.staff_name,
            'date': result.date,
            'total_commission': float(result.total_commission),
            'commission_count': result.commission_count
        } for result in results]
        
        return {
            'status': 'success',
            'message': '获取成功',
            'data': commission_summary
        }, 200

@api.route('/store/cal', strict_slashes=False)
class StoreCost(Resource):
    @api.doc('店铺统计')
    @token_required
    def get(self):
        """获取当前账户下的统计信息"""
        manager_id = g.current_identity.user_id
        store_id = request.args.get('store_id')

        if not manager_id:
            return {
               'status': 'error',
               'message': '未登录或无效的用户'
            }, 401

                # 1. 获取店铺信息
        if store_id:
            # 查询店铺 - 同时检查manager_id和UserStore的owner角色
            from models.user_store import UserStore
            
            # 基础查询条件
            base_conditions = [
                Store.is_deleted == False,
                Store.store_id == store_id,  # 添加store_id过滤条件
                or_(
                    UserStore.role == 'owner',
                    and_(
                        Store.manager_id == UserStore.user_id,
                        UserStore.role == 'manager'
                    )
                )
            ]
            
            # 根据用户角色添加过滤条件
            if 'admin' not in g.current_identity.roles.split(','):
                user_id = g.current_identity.user_id
                base_conditions.append(
                    or_(
                        UserStore.user_id == user_id,
                        Store.manager_id == user_id
                    )
                )
            elif (user_id := request.args.get('user_id')):
                base_conditions.append(
                    or_(
                        UserStore.user_id == user_id,
                        Store.manager_id == user_id
                    )
                )
            
            # 添加店铺名称模糊查询
            if (name := request.args.get('name')):
                base_conditions.append(Store.name.like(f'%{name}%'))
            
            # 构建查询
            query = db.session.query(Store).join(
                UserStore,
                Store.store_id == UserStore.store_id
            ).filter(*base_conditions).order_by(desc(Store.id))

            managed_stores = query.all()
        else:
            # 否则查询所有管理的店铺
            # 查询所有管理的店铺 - 包括manager_id匹配和UserStore中role为owner的记录
            from models.user_store import UserStore
            managed_stores = db.session.query(Store).distinct().join(
                UserStore,
                Store.store_id == UserStore.store_id
            ).filter(
                or_(
                    Store.manager_id == manager_id,
                    and_(
                        UserStore.user_id == manager_id,
                        UserStore.role == 'owner'
                    )
                ),
                Store.is_deleted == False
            ).all()
        
        # 1. 获取店铺数、员工数、客户数
        # 获取当前用户管理的店铺
        # managed_stores = Store.query.filter_by(manager_id=manager_id).all()
        store_count = len(managed_stores)
        
        # 获取员工数和客户数
        staff_count = 0
        customer_count = 0
        store_ids_uuid = [store.store_id for store in managed_stores]
        store_ids = [store.id for store in managed_stores]
        
        if store_ids_uuid:
            # 查询所有关联用户
            from models.user_store import UserStore
            user_stores = UserStore.query.filter(
                UserStore.store_id.in_(store_ids_uuid)
            ).all()
            
            # 统计员工和客户数量
            for us in user_stores:
                if us.role in ['staff', 'manager', 'owner']:
                    staff_count += 1
                elif us.role == 'customer':
                    customer_count += 1
        
        # 2. 获取订单和财务数据
        order_count = 0
        total_order_amount = 0.0
        recharge_count = 0
        per_count = 0
        total_per_amount = 0.0
        total_recharge_amount = 0.0
        total_cost = 0.0
        total_commission_cost = 0.0
        
        if store_ids:
            # 查询消费记录
            consumptions = CardConsumption.query.filter(
                CardConsumption.store_id.in_(store_ids),
                CardConsumption.is_invalid == False
            ).all()
            
            for c in consumptions:
                if c.transaction_type in [4]:  # 卡包订单消费
                    order_count += 1
                    total_order_amount += c.amount_used
                elif c.transaction_type == 1:  # 客户总充值
                    recharge_count += 1
                    total_recharge_amount += c.amount_used
                elif c.transaction_type == 3:  # 现金单次消费
                    per_count += 1
                    total_per_amount += c.amount_used
                elif c.transaction_type in [2, 5, 6]:  # 成本支出(包括直接成本支出、卡包提成和单笔业务提成)
                    total_cost += c.amount_used
                    if c.transaction_type in [5, 6]:  # 总提成支出(卡包提成和单笔业务提成)
                        total_commission_cost += c.amount_used
        
        return {
            'status': 'success',
            'message': '获取统计信息成功',
            'data': {
                'store_count': store_count,
                'staff_count': staff_count,
                'customer_count': customer_count,
                'order_count': order_count,
                'total_order_amount': round(total_order_amount, 2),
                'recharge_count': recharge_count,
                'per_count': per_count,
                'total_per_amount': round(total_per_amount, 2),
                'total_recharge_amount': round(total_recharge_amount, 2),
                'total_cost': round(total_cost, 2),
                'total_commission_cost': round(total_commission_cost, 2),
                'net_income': round(total_recharge_amount + total_per_amount - total_cost, 2)
            }
        }, 200

@api.route('/staff/performance', strict_slashes=False)
class StaffPerformance(Resource):
    @api.doc('获取店铺员工业绩数据', params={
        'store_id': '店铺ID(必填)',
        'type': '时间类型(day/month/year, 默认day)',
        'start_date': '开始日期',
        'end_date': '结束日期',
        'page': '页码',
        'limit': '每页数量'
    })
    @api.marshal_with(staff_performance_response)
    @token_required
    def get(self):
        """获取员工业绩数据"""
        store_id = request.args.get('store_id')
        time_type = request.args.get('type', 'day')  # 默认按天统计
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 10))
        
        if not store_id:
            return {
                'status': 'error',
                'message': '店铺ID为必填项'
            }, 400

        # 查询店铺信息
        store = Store.query.filter_by(store_id=store_id).first()
        if not store:
            return {
                'status': 'error',
                'message': '店铺不存在'
            }, 404

        # 根据时间类型设置日期字段
        if time_type == 'year':
            date_field = CardConsumption.consumption_year
        elif time_type == 'month':
            date_field = CardConsumption.consumption_month
        else:  # day
            date_field = CardConsumption.consumption_day

        # 构建基础查询
        base_query = db.session.query(
            CardConsumption.staff_id,
            User.name.label('staff_name'),
            CardConsumption.consumption_day,
            CardConsumption.consumption_month,
            CardConsumption.consumption_year,
            db.func.sum(
                db.case(
                    (CardConsumption.transaction_type.in_([1, 3, 4]), CardConsumption.amount_used),
                    else_=0
                )
            ).label('performance'),
            db.func.sum(
                db.case(
                    (CardConsumption.transaction_type.in_([5, 6, 9, 10]), CardConsumption.amount_used),
                    else_=0
                )
            ).label('commission')
        ).join(
            User, User.id == CardConsumption.staff_id
        ).filter(
            CardConsumption.store_id == store.id,
            CardConsumption.is_invalid == False
        )

        # 添加日期筛选
        start_date = request.args.get('start_date')
        if start_date:
            start_date_int = int(datetime.strptime(start_date, '%Y-%m-%d').strftime('%Y%m%d'))
            base_query = base_query.filter(CardConsumption.consumption_day >= start_date_int)

        end_date = request.args.get('end_date')
        if end_date:
            end_date_int = int(datetime.strptime(end_date, '%Y-%m-%d').strftime('%Y%m%d'))
            base_query = base_query.filter(CardConsumption.consumption_day <= end_date_int)

        # 获取总数
        total = base_query.group_by(
            CardConsumption.staff_id,
            User.name,
            CardConsumption.consumption_day,
            CardConsumption.consumption_month,
            CardConsumption.consumption_year
        ).count()

        # 分页查询
        results = base_query.group_by(
            CardConsumption.staff_id,
            User.name,
            CardConsumption.consumption_day,
            CardConsumption.consumption_month,
            CardConsumption.consumption_year
        ).order_by(
            db.desc('performance')
        ).offset((page - 1) * limit).limit(limit).all()

        # 格式化结果
        performance_data = {
            'list':[{
                'staff_id': result.staff_id,
                'staff_name': result.staff_name,
                'consumption_day': result.consumption_day,
                'consumption_month': result.consumption_month,
                'consumption_year': result.consumption_year,
                'performance': float(result.performance or 0),
                'commission': float(result.commission or 0)
                } for result in results],
            'pagination': {
                'total': total,
                'page': page,
                'limit': limit
                }
        }

        return {
            'status': 'success',
            'message': '获取员工业绩数据成功',
            'data': performance_data,
        }, 200

@api.route('/cash_payment', strict_slashes=False)
class CashPayment(Resource):
    @api.doc('现金支付记录')
    @api.expect(card_consumption_model)
    @api.marshal_with(card_consumption_response)
    @token_required
    def post(self):
        """现金单次支付记录"""
        data = request.get_json()
        
        consumption = CardConsumption(
            income_type=1,  # 收入
            transaction_type=3,  # 现金单次消费
            store_id=data['store_id'],
            user_id=data.get('user_id'),
            staff_id=data['staff_id'],
            product_id=data['product_id'],
            consumption_date=datetime.now(),
            amount_used=data['amount_used'],
            description=data.get('description', '现金消费')
        )
        
        db.session.add(consumption)
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '支付记录创建成功',
            'data': consumption.to_dict()
        }, 201

@api.route('/list', strict_slashes=False)
class CardConsumptionList(Resource):
    @api.doc('获取消费记录列表', params={
        'store_id': '店铺ID',
        'transaction_type': '交易类型',
        'income_type': '收支类型',
        'start_date': '开始日期',
        'end_date': '结束日期'
    })
    @api.marshal_with(card_consumption_list_response)
    @token_required
    def get(self):
        """获取消费记录列表"""
        query = CardConsumption.query.filter_by(is_invalid=False)
        
        store_id = request.args.get('store_id')
        if store_id:
            query = query.filter(CardConsumption.store_id == store_id)
            
        transaction_type = request.args.get('transaction_type')
        if transaction_type:
            query = query.filter(CardConsumption.transaction_type == transaction_type)
            
        income_type = request.args.get('income_type')
        if income_type:
            query = query.filter(CardConsumption.income_type == income_type)
            
        start_date = request.args.get('start_date')
        if start_date:
            query = query.filter(CardConsumption.consumption_date >= start_date)
            
        end_date = request.args.get('end_date')
        if end_date:
            query = query.filter(CardConsumption.consumption_date <= end_date)
        
        consumptions = query.order_by(CardConsumption.consumption_date.desc()).all()
        
        return {
            'status': 'success',
            'message': '获取成功',
            'data': [consumption.to_dict() for consumption in consumptions]
        }, 200

@api.route('/user/transactions', strict_slashes=False)
class UserTransactions(Resource):
    @api.doc('获取用户收支明细数据', params={
        'user_id': '用户ID(必填)',
        'type': '类型(1:提成记录, 2:消费记录)',
        'start_date': '开始日期',
        'end_date': '结束日期',
        'page': '页码',
        'limit': '每页数量'
    })
    @api.marshal_with(staff_performance_list_response)
    @token_required
    def get(self):
        """获取用户收支明细数据"""
        user_id = request.args.get('user_id')
        type_filter = request.args.get('type', '1')  # 默认为1，显示提成记录
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 10))
        
        if not user_id:
            return {
                'status': 'error',
                'message': '用户ID为必填项'
            }, 400

        # 查询用户信息
        user = User.query.filter_by(id=user_id, is_deleted=False).first()
        if not user:
            return {
                'status': 'error',
                'message': '用户不存在'
            }, 404

        # 根据type参数设置交易类型过滤条件
        transaction_types = [5, 6, 9, 10] if type_filter == '1' else [1, 3, 4]
        
        # 构建基础查询
        base_query = db.session.query(
            CardConsumption,
            User.name.label('user_name'),
            Product.name.label('product_name')
        ).join(
            User, User.id == CardConsumption.staff_id
        ).outerjoin(
            Product, Product.id == CardConsumption.product_id
        ).filter(
            CardConsumption.staff_id == user.id,
            CardConsumption.is_invalid == False,
            CardConsumption.transaction_type.in_(transaction_types)
        )

        # 添加日期筛选
        start_date = request.args.get('start_date')
        if start_date:
            start_date_int = int(datetime.strptime(start_date, '%Y-%m-%d').strftime('%Y%m%d'))
            base_query = base_query.filter(CardConsumption.consumption_day >= start_date_int)

        end_date = request.args.get('end_date')
        if end_date:
            end_date_int = int(datetime.strptime(end_date, '%Y-%m-%d').strftime('%Y%m%d'))
            base_query = base_query.filter(CardConsumption.consumption_day <= end_date_int)

        # 获取总数
        total = base_query.count()

        # 分页查询
        results = base_query.order_by(
            db.desc(CardConsumption.consumption_date)
        ).offset((page - 1) * limit).limit(limit).all()

        # 格式化结果
        transactions_data = {
            'list': [{
                'id': result.CardConsumption.id,
                'transaction_type': result.CardConsumption.transaction_type,
                'income_type': result.CardConsumption.income_type,
                'amount_used': float(result.CardConsumption.amount_used or 0),
                'consumption_date': result.CardConsumption.consumption_date,
                'consumption_day': result.CardConsumption.consumption_day,
                'consumption_month': result.CardConsumption.consumption_month,
                'consumption_year': result.CardConsumption.consumption_year,
                'user_name': result.user_name,
                'product_name': result.product_name,
                'description': result.CardConsumption.description
            } for result in results],
            'pagination': {
                'total': total,
                'page': page,
                'limit': limit
            }
        }

        return {
            'status': 'success',
            'message': '获取用户收支明细数据成功',
            'data': transactions_data
        }, 200